<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>并发测试</title>
    <link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="css/base.css">
</head>

<body>
<div id="app" @click="historyShow = false" v-cloak>
    <div class="container">
        <h3 class="text-center">并发测试</h3>
        <br>
        <div class="input-group">
            <span class="input-group-addon">公用地址</span>
            <input type="text" class="form-control" v-model="baseURL" placeholder="请输入公用请求地址 ">
        </div>
        <div class="input-group">
            <span class="input-group-addon">请求地址</span>
            <input type="text" class="form-control" @click.stop="historyShow = true" @keyup="search" v-model="url"
                   placeholder="请输入请求地址">
            <div class="toggle" v-show="historyShow">
                <ul>
                    <li v-for="(v,index) in historys" @click="selectHistory(index)">{{v.baseURL + v.url}}
                        <span class="date">{{v.upDate}}</span>
                    </li>
                </ul>
            </div>
        </div>
        <div class="input-group">
            <span class="input-group-addon">并发次数</span>
            <input type="number" class="form-control" v-model="postSize" placeholder="请输入并发次数 " style="width: 100px;">
        </div>
        <div class="input-group">
            <span class="input-group-addon">请求方式</span>
            <select class="form-control" v-model="type">
                <option value="GET">GET</option>
                <option value="POST">POST</option>
            </select>
        </div>
        <div>请求头</div>
        <div class="table-wrapper">
            <table class="table">
                <thead>
                <tr>
                    <th style="width:100px;">key</th>
                    <th>value</th>
                    <th style="width:100px;">操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="(v,index) in headers" :key="index">
                    <td>
                        <input type="text" class="form-control" v-model=v.key>
                    </td>
                    <td>
                        <input type="text" class="form-control" v-model=v.value>
                    </td>
                    <td>
                        <button class="btn btn-sm btn-success" @click="addHeader" v-if="index === 0">添加
                        </button>
                        <button class="btn btn-danger btn-sm" v-else @click="removeHeader(index)">删除
                        </button>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="input-group">
            <span class="input-group-addon top">请求参数</span>
            <textarea name="" style="width: 100%;" class="form-control" v-model="body"
                      placeholder="请输入请求参数（json格式）"></textarea>
        </div>
        <div class="text-center">
            <button class="btn btn-info submit" @click="submit">提交</button>
            <button class="btn" @click="resetForm">清空</button>
        </div>
        <br>
        <div class="row">
            <div class="col-xs-8">
                <pre class="returndata"  style="height: 400px;" v-html='res'></pre>
            </div>
            <div class="col-xs-4">
                <pre class="returndata" style="height: 190px;min-height: 0;" v-html='message.join("")'></pre>
                <pre class="returndata" style="height: 200px;min-height: 0;"  v-html='errorMsg.join("")'></pre>
            </div>
        </div>
        <br>
    </div>
</div>
</body>
<script src="https://cdn.bootcss.com/vue/2.5.9/vue.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.17.1/axios.js"></script>
<script src="js/formatJson.js"></script>
<script>
    // axios.interceptors.request.use(config => {
    //     config.headers.ispToken = '35122050f56becc997c825ff7ee54cb7';
    //     return config;
    // });
    let vm = new Vue({
        el: '#app',
        data: {
            historyShow: false,
            baseURL: 'http://172.17.1.76:8080/ej-isp-api',
            url: '/msp/selectTops',
            type: 'POST',
            postSize: 50,
            headers: [{
                key: 'ispToken',
                value: '8599f216ae1a4a44b8280b8ee7f06103 '
            }],
            body: '',
            res: '',
            historys: [],
            message:[],
            errorMsg:[]
        },
        mounted() {
            this.historys = this.getHistory();
        },
        methods: {
            submit() {
                let type = this.type;
                let head = this.headers;
                let url = this.baseURL + this.url;
                let data = {};
                if (this.body.trim().length === 0 || this.body === undefined) {
                    data = {};
                } else {
                    data = JSON.parse(this.body)
                }
                let headers = {};
                for (let i of head) {
                    headers[i.key] = i.value;
                }
                //  储存为历史
                this.save(headers);
                //  更新历史
                this.historys = this.getHistory();
                let D = Date.parse(new Date());
                this.res = [];
                this.errorMsg = [];
                this.message = [];
                for(let i = 0 ; i < this.postSize;i++){
                    this.http(type,url,headers,data,i,D);
                }
            },
            // 发送请求
            http(type,url,headers,data,i,D){
                //  提交
                if (type === 'POST') {
                    axios({
                        url,
                        method: type,
                        headers,
                        data
                    }).then(res => {
                        let data = JSON.stringify(res.data);
                        // this.res.push(formatJson(data));
                        this.res=formatJson(data);
                        // console.log(`第${i+1}次获取成功`);
                        let d = Date.parse(new Date()) - D;
                        console.log(`本次用时${d/1000}s，第${i+1}次`);
                        this.message.push(`本次用时${d/1000}s，第${i+1}次<br>`);
                    }).catch(e=>{
                        this.errorMsg.push(`第${i+1}次获取失败<br>`);
                        console.error({
                            num:i,
                            msg:'获取失败',
                            err:e
                        })
                    })
                } else if (type === 'GET') {
                    axios({
                        url,
                        method: type,
                        params: data,
                        headers
                    }).then(res => {
                        let data = JSON.stringify(res.data)
                        // this.res.push(formatJson(data));
                        this.res=formatJson(data);
                        this.message.push(`本次用时${d/1000}s，第${i+1}次<br>`);
                    }).catch(e=>{
                        this.errorMsg.push(`第${i+1}次获取失败/n`);
                        console.error({
                            num:i,
                            msg:'获取失败',
                            err:e
                        })
                    })
                }
            },
            // 添加请求头
            addHeader() {
                let obj = {
                    key: '',
                    value: ''
                };
                this.headers.push(obj);
            },
            // 删除请求头
            removeHeader(index) {
                this.headers.splice(index, 1);
            },
            // 清空表单
            resetForm() {
                this.url = '';
                this.body = '';
                this.res = '';
            },
            // 保存历史记录
            save(headers = {}) {
                let type = this.type;
                let url = this.url;
                let body = this.body;
                let baseURL = this.baseURL;
                let D = new Date();
                let upDate = D.getFullYear() + '-' + (D.getMonth() + 1) + '-' + (D.getDate()) + ' ' + D.getHours() + ':' + D.getMinutes() + ':' + D.getSeconds();
                let obj = {
                    url,
                    body,
                    baseURL,
                    type,
                    headers,
                    upDate
                };
                // 取出储存的数据并且格式化
                let storageData = this.getHistory();

                // 判断是否已存在此条记录
                let ishave = false;
                for (let i of storageData) {
                    let u = this.baseURL + this.url;
                    let iu = i.baseURL + i.url;
                    if (u === iu) {
                        storageData[i] = obj;
                        ishave = true;
                    }
                }
                if (!ishave) {
                    storageData.push(obj);
                }
                // 转为JSON储存
                localStorage.setItem('historyData', JSON.stringify(storageData));
            },
            // 取出历史记录并格式化
            getHistory() {
                let storageData = localStorage.getItem('historyData');
                if (storageData === null ||
                    storageData.trim().length === 0 ||
                    storageData === undefined) {
                    storageData = [];
                } else {
                    storageData = JSON.parse(storageData);
                }
                return storageData;
            },
            // 选择历史记录事件
            selectHistory(index) {
                let data = this.historys[index];
                this.url = data.url;
                this.baseURL = data.baseURL;
                this.type = data.type;
                this.body = data.body;
                let h = [];
                for (let i in data.headers) {
                    let a = {
                        key: i,
                        value: data.headers[i]
                    };
                    h.push(a);
                }
                this.headers = h;
                this.historyShow = false;
            },
            search() {
                let val = this.baseURL + this.url;
                let his = this.getHistory();
                let h = []
                for (let i of his) {
                    let u = i.baseURL + i.url;
                    if (u.indexOf(val) != '-1') {
                        h.push(i);
                    }
                }
                if (val.trim().length === 0 || val === null || val === undefined) {
                    this.historys = this.getHistory();
                } else {
                    this.historys = h;
                }
            }
        }
    });
</script>

</html>